<template>
  <div style="position: relative">
    <div class="loading" v-if="loadingFlag"><a-spin></a-spin></div>
    <a-card :bordered="false" style="">
      <div style="display: flex; flex-wrap: wrap">
        <head-info title="设备名称" :content="devName" :bordered="true"/>
        <head-info title="设备编号" :content="devCode" :bordered="true"/>
        <head-info title="设备参数" :content="propertyCount + '个'"/>
      </div>
    </a-card>
    <div class="quick-option">
      <div class="quick-btn" @click="$router.push('/dev/index')">
        <a-button type="dashed">返回</a-button>
      </div>
      <div class="quick-btn">
        <a-button type="warning" style="background: rgb(76,211,146); color: #fff" @click="changePropertySubmit">保存修改</a-button>
      </div>
      <div class="quick-btn" @click="changeAllStatus('show')">
        <a-button type="primary">全部显示</a-button>
      </div>
      <div class="quick-btn" @click="changeAllStatus('hidden')">
        <a-button type="danger">全部隐藏</a-button>
      </div>
    </div>
    <div>
      <a-list class="main-list" :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 3, xl: 4, xxl: 4 }" :data-source="propertyList">
        <a-list-item slot="renderItem" slot-scope="item, index" class="item-list-m">
          <a-card :title="item.DisplayName">
            <a slot="extra">
              <a-popconfirm placement="topRight" cancel-text="" ok-text="确定" @confirm="propertyConfirm(item, index, 'name')">
                <template slot="title">
                  <p><a-input placeholder="显示名称" v-model="displayName" allowClear/></p>
                </template>
                <a-icon slot="icon" type="question-circle-o" style="color: red" />
                <span style="cursor: pointer; color: #E26B0D"><a-icon type="edit" /> 修改名称</span>
              </a-popconfirm>
            </a>
            <div class="field-main">
              <div class="field-name">字段名</div>
              <div class="field-getPropertyvalue" v-text="item.FieldName"></div>
            </div>
            <div class="field-main m-t-10" v-if="item.Unit && item.Unit != ''">
              <div class="field-name">
                <a-popconfirm placement="topLeft" cancel-text="" ok-text="确定" @confirm="propertyConfirm(item, index, 'unit')">
                  <template slot="title">
                    <p><a-input placeholder="单位" v-model="unit" allowClear/></p>
                  </template>
                  单位 <span style="color: #E26B0D"><a-icon type="form" /></span>
                </a-popconfirm>
              </div>
              <div class="field-getPropertyvalue" v-text="item.Unit"></div>
            </div>
            <div class="field-main m-t-10">
              <div class="field-name">显示状态</div>
              <div class="field-value status">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>点击切换</span>
                  </template>
                  <a-switch checked-children="显示" un-checked-children="隐藏" v-model="item.showStatus" @change="(checked, event) => statusConfirm(index, checked, item)"/>
                </a-tooltip>
              </div>
            </div>
            <div class="field-main field-map m-t-10" style="align-items: flex-start">
              <div class="field-name" style="cursor: pointer" @click="showModal(index,null, item)">属性列表 <span style="color: #40A636"><a-icon type="plus-square" /></span></div>
              <div class="field-value map">
                <div class="map-m" v-for="(v, k) in item.ValueMap" :key="k">
                  <div class="m-key" v-html="`<a>${v.Value}</a>`"></div>
                  <div class="m-icon"><a-icon type="right" /></div>
                  <div class="m-value" v-text="v.DisplayValue"></div>
                  <div class="m-btns">
                    <div class="btn-m btn-edit" title="编辑" @click="showModal(index, v, item, k)">
                      <a-icon type="edit" />
                    </div>
                    <div class="btn-m btn-del" title="删除" @click="showConfirm(index, item, k)">
                      <a-icon type="delete" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </a-card>
        </a-list-item>
      </a-list>
    </div>
    <!-- 编辑参数 -->
    <a-modal v-model="propertyFlag" :title="propertyModalTitle" @ok="propertySubmit">
      <a-form-model :model="propertyObj" :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }">
        <a-form-model-item label="键 值">
          <a-input v-model="propertyObj.Value" type="number" placeholder="请输入键值"/>
        </a-form-model-item>
        <a-form-model-item label="键 名">
          <a-input v-model="propertyObj.DisplayValue"  placeholder="请输入键名" allowClear/>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
  import HeadInfo from '../../components/tool/HeadInfo'
  import { getProperty, changeProperty } from '@/services/dev'
  import { filterArray, isLabel } from '@/utils/util'
  export default {
    name: "SetUp",
    data() {
      return {
        loadingFlag: false,
        devCode: '',
        devName: '',
        propertyCount: 0,
        propertyList: [],
        propertyListIndex: [],// 编辑的列表索引
        displayName: '',
        unit: '',
        propertyObj: {
          Value: '',
          DisplayValue: ''
        },
        propertyModalTitle: '',
        propertyFlag:false,
        propertyIndex: null,
        tempData: {}
      }
    },
    computed: {
      statusName(e) {
        return e => {
          if(!e) {
            return `<span style="color: #67c23a">显示</span>`
          } else return `<span style="color: #f56c6c">隐藏</span>`
        }
      }
    },
    watch: {
      //监听route变化强制更新
      '$route': function (newVal) {
        if(newVal.path == '/dev/setup') {
          //初始化数据
          this.displayName = ''
          this.unit = ''
          this.init()
        } else {
          console.log(newVal);
        }
      }
    },
    components: {
      HeadInfo
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        const {devCode, devName} = this.$route.query
        if(devCode == '') {
          this.$router.back()
          return
        }
        this.devCode = devCode
        this.devName = devName
        this.getPropertyList()
      },
      async getPropertyList() {
        let res = await getProperty(this.devCode)
        if(res.Code == 0) {
          const labelFlag = isLabel(res.Data)
          console.log(labelFlag);
          let propertyList = labelFlag ? filterArray(res.Data) : res.Data //全是label为环采或者气象站，只显示有效值
          propertyList.forEach(async item => {
            item.showStatus = !item.NotShow
          })
          this.propertyCount = propertyList.length
          this.propertyList = propertyList
        } else {
          this.$message.error(res.Message)
        }
      },
      changePropertySubmit() {
        this.loadingFlag = true
        const data = {
          DevCode: this.devCode,
          Fields: this.propertyList
        }
        changeProperty(data).then(res => {
          //初始化数据
          this.displayName = ''
          this.unit = ''
          if(res.Code == 0) {
            this.$message.success("修改成功")
            this.loadingFlag = false
            this.getPropertyList() //刷新列表数据
          } else {
            this.$message.error(res.Message)
          }
        }).catch(err => {
          console.log(err);
          this.$message.error("修改失败")
          //初始化数据
          this.displayName = ''
          this.unit = ''
        })
      },
      //确定修改名称、单位
      propertyConfirm(obj, index, type) {
        if(type == 'name') {
          if(this.displayName == '') {
            this.$confirm({
              content: '请输入名称',
              icon: 'warning',
              centered: true
            })
            return
          } else {
            this.propertyList[index].DisplayName = this.displayName
          }
        }
        if(type == 'unit') {
          if(this.unit == '') {
            this.$confirm({
              content: '请输入单位名称',
              icon: 'warning',
              centered: true
            })
            return
          } else {
            this.propertyList[index].Unit = this.unit
          }
        }
        console.log(this.propertyList);
      },
      //修改显示状态
      statusConfirm(index, e, obj) {
        console.log(index, e, obj);
        this.propertyList[index].NotShow = !e
        console.log(this.propertyList);
      },
      //新增、修改属性弹出modal
      showModal(listIndex, valObj, item, index=null) {
        console.log(valObj);
        this.propertyListIndex = listIndex
        this.propertyFlag = true
        let fields = JSON.parse(JSON.stringify(this.propertyList))
        fields[listIndex] = {
          FieldName: item.FieldName,
          DisplayName: item.DisplayName,
          Unit: item.Unit,
          ValueMap: item.ValueMap,
          NotShow: item.NotShow
        }
        // 组装临时文件
        this.tempData = {
          DevCode: this.devCode,
          Fields: fields
        }
        if(index != null) {
          //编辑
          this.propertyModalTitle = '属性编辑'
          this.propertyIndex = index
          const value = valObj.Value
          const displayName = valObj.DisplayValue
          this.propertyObj.Value = value
          this.propertyObj.DisplayValue = displayName
        } else {
          //新增
          this.propertyModalTitle = '属性新增'
          this.propertyObj = this.$options.data().propertyObj //初始对象
        }
      },
      //新增、修改属性提交
      propertySubmit() {
        if(this.propertyObj.Value == '') {
          this.$message.warning("键值不能为空")
          return
        }
        if(this.propertyObj.DisplayValue == '') {
          this.$message.warning("键名不能为空")
          return
        }
        if(this.propertyIndex === null) {
          console.log('新增')
          this.propertyList[this.propertyListIndex].ValueMap.push(this.propertyObj) //push新数据
          console.log(this.propertyList);
        } else {
          console.log('编辑')
          this.propertyList[this.propertyListIndex].ValueMap[this.propertyIndex] = this.propertyObj
          console.log(this.propertyList);
        }
        this.propertyObj = this.$options.data().propertyObj
        this.propertyIndex = null //重置索引，不然修改一次后新增也会变成编辑
        this.propertyFlag = false // 统一关闭弹窗
      },
      //删除属性
      showConfirm(listIndex, obj, index) {
        this.$confirm({
          content: '确定删除该项?',
          icon: 'warning',
          centered: true,
          onOk: () => {
            console.log(obj, index);
            this.propertyList[listIndex].ValueMap.splice(index, 1)
            console.log(this.propertyList);
          },
          onCancel: () => {
            this.$message.warning('您取消了操作')
          }
        })
      },
      //修改所有属性的状态
      changeAllStatus(type) {
        console.log(type);
        this.loadingFlag = true
        let status = ''
        if(type === 'show') {
          status = false
        }
        if(type === 'hidden') {
          status = true
        }
        this.propertyList.forEach(item => {
          item.NotShow = status
        })
        const data = {
          DevCode: this.devCode,
          Fields: this.propertyList
        }
        changeProperty(data).then(res => {
          if(res.Code == 0) {
            this.$message.success("操作成功")
            this.getPropertyList() // 刷新列表数据
          } else {
            this.$message.error(res.Message)
            this.getPropertyList() // 刷新列表数据
          }
        }).catch(err => {
          console.log(err);
          this.$message.error("操作失败")
          this.getPropertyList() // 刷新列表数据
        })
        this.loadingFlag = false
      },
      showEditModal(e) {
        this.editFlag = true
      },
    }
  }
</script>

<style scoped lang="less">
  .loading {
    position: absolute;
    z-index: 99999;
    background: rgba(0,0,0,.3);
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .quick-option {
    margin: 15px 0;
    display: flex;
    justify-content: center;
    .quick-btn {
      margin-left: 10px;
    }
    .quick-btn:first-child {
      margin: 0;
    }
  }
  .item-list-m {
    display: inline-block;
    float: none;
    vertical-align: top;
    .field-main {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      align-items: center;
      .map {
        .map-m {
          margin-top: 5px;
          display: flex;
          align-items: center;
          .m-key {
            background: #f0f0f0;
            border:1px dashed #fff;
            padding: 5px 10px;
            border-radius: 2px;
          }
          .m-icon {
            margin-left: 10px;
          }
          .m-value {
            margin-left: 10px;
            background: #f0f0f0;
            border:1px dashed #fff;
            padding: 5px 10px;
            border-radius: 2px;
          }
          .m-btns {
            flex: 1;
            display: flex;
            justify-content: flex-end;
            margin-left: 10px;
            .btn-m {
              font-size: 13px;
              color: #fff;
              cursor: pointer;
              padding: 2px 5px;
              border-radius: 50px;
            }
            .btn-edit {
              background: #E26B0D;
            }
            .btn-del {
              margin-left: 5px;
              background: red;
            }
          }
        }
      }
    }
    .field-map {
      padding: 0 10px 10px 0;
      border-radius: 5px;
      box-shadow: 5px 5px 5px #dedede;
    }
  }
  .m-t-10 {
    margin-top: 10px;
  }
  .name-action {
    margin-top: 10px;
    color: #E26B0D;
    cursor: pointer;
  }
</style>
